package com.neuedu.handler;

import com.alibaba.fastjson.JSONObject;
import com.neuedu.exception.UserNoLoginException;
import com.neuedu.myUtil.JwtUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Enumeration;

public class Interceptor implements HandlerInterceptor {


	private final Logger logger = LoggerFactory.getLogger(Interceptor.class);

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
		/** 地址过滤 */
		String uri = request.getRequestURI();
		logger.info("url="+uri);
		if (1==1){
			return true;
		}
		if (uri.endsWith("/login")||uri.endsWith("/error")) {
			return true;
		}
		// System.out.println(request);
		String token = request.getHeader("Authorization");// 从 http 请求头中取出 token
		// 如果不是映射到方法直接通过
		if (!(handler instanceof HandlerMethod)) {
			return true;
		}
		// HandlerMethod handlerMethod = (HandlerMethod) object;
		// Method method = handlerMethod.getMethod();
		if (token == null) {
			throw new UserNoLoginException();
		}
		JwtUtil.isExpire(token);

		StringBuilder sb = new StringBuilder(1000);

		//获取请求参数
		Enumeration em = request.getParameterNames();
		JSONObject data = new JSONObject();
		while (em.hasMoreElements()) {
			String name = (String) em.nextElement();
			String value = request.getParameter(name);
			data.put(name,value);
		}
		sb .append("-------------------------------------------------------------\n");
		HandlerMethod h = (HandlerMethod) handler;
		sb.append("Controller: ").append(h.getBean().getClass().getName()).append("\n");
		sb.append("Method    : ").append(h.getMethod().getName()).append("\n");
		sb.append("Params    : ").append(data).append("\n");
		sb.append("URI       : ").append(request.getRequestURI()).append("\n");
		sb.append("URL       : ").append(request.getRequestURL()).append("\n");
		sb .append("-------------------------------------------------------------\n");
		System.out.println(sb.toString());
		return  true;
	}
}